package com.lemon.exam.common.config;

import com.lemon.exam.common.converter.*;
import io.r2dbc.spi.ConnectionFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.r2dbc.convert.R2dbcCustomConversions;
import org.springframework.data.r2dbc.dialect.MySqlDialect;
import org.springframework.data.r2dbc.repository.config.EnableR2dbcRepositories;
import org.springframework.r2dbc.connection.R2dbcTransactionManager;
import org.springframework.transaction.ReactiveTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;

/**
 * R2dbc 配置类
 *
 * @author Lemon
 * @since 2025/3/24 11:47
 */
@Configuration
@EnableTransactionManagement // 确保开启事务管理
@EnableR2dbcRepositories(basePackages = "com.lemon.exam.repository")
public class R2dbcConfiguration {
    /**
     * 自定义转换器
     *
     * @return
     */
    @Bean
    public R2dbcCustomConversions conversions() {
        return R2dbcCustomConversions.of(MySqlDialect.INSTANCE,
                new UserConverter(),
                new MapConverter(),
                new MenuConverter(),
                new PaperConverter(),
                new UserRoleMenuResourceConverter(),
                new ClassGradeUserJobConverter()
        );
    }

    /**
     * 配置响应式事务管理器
     *
     * @param connectionFactory
     * @return
     */
    @Bean
    public ReactiveTransactionManager transactionManager(ConnectionFactory connectionFactory) {
        return new R2dbcTransactionManager(connectionFactory);
    }
}
